from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.urls import reverse
from myadmin.views import OpenStackToken
from myadmin.views import OpenStackSubnet

# 默认情况下Django处于安全考虑，不允许后端直接输出html至前端，前端不会喧染
# 可以在后台使用mark_safe()将要显示的html转换后，前端可以正常输出html
from django.utils.safestring import mark_safe

# Create your views here.

import requests,json,time

import os
from pathlib import Path

import myadmin.views.OpenStackToken

# 导入日志处理模块
import logging
# -----------logger-----------
# get logger
logger = logging.getLogger(__name__)
# level
logger.setLevel(logging.DEBUG)
# format
format = logging.Formatter('%(asctime)s %(message)s')
# to console
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(format)
logger.addHandler(stream_handler)
# -----------logger-----------


url = OpenStackToken.networkurl
headers = OpenStackToken.getToken()

def index(request):
    # 通过render方法让html模板喧染页面
    networklist = json.loads(requests.get(url, headers=headers).text)
    # 定义返回结果数据集
    datadict = []

    for network in networklist['networks']:
        networkid = network['id']
        networkname = network['name']
        subnets = ""
        availability_zones = ""

        obj_subnets = network['subnets']
        obj_ava_zones = network['availability_zones']

        # 依次获取子网信息
        for subid in obj_subnets:
            subinfos = OpenStackSubnet.getSubnet(subid)['subnet']
            print(subinfos)
            subname = subinfos["name"]
            cidr = subinfos["cidr"]
            gateway_ip = subinfos["gateway_ip"]
            temp = "<font color='#77aa88'><b>子网名称："+subname+" "+cidr+" 网关："+gateway_ip+"</b></font><br>"
            subnets += temp
        # 依次处理zone信息

        for zoneinfo in obj_ava_zones:
            temp = "<font color='#aa2299'>"+zoneinfo+"</font><br>"
            availability_zones += temp

        temp = {"id": networkid, "name": networkname,"subnets": mark_safe(subnets), "status": network['status'], "shared": network['shared'],
                "admin_state_up": network['admin_state_up'], "availability_zones": mark_safe(availability_zones)}
        datadict.append(temp)


    context = {"networklist": datadict}
    return render(request,"myadmin/network/index.html",context)

def add(request):
    '''加载添加信息'''
    return render(request, "myadmin/network/networkadd.html")

def insert(request):
    '''执行网络信息添加'''
    try:
        ckadmin = False
        ckshare = False
        enabledhcp = False

        if 'ckadmin' in request.POST:
            ckadmin = True
        if 'ckshare' in request.POST:
            ckshare = True
        if 'enabledhcp' in request.POST:
            enabledhcp = True

        networkname = request.POST['networkname']
        subnetname = request.POST['subnetname']
        cird = request.POST['cird']
        gateway = request.POST['gateway']
        iprange = request.POST['iprange']
        dns = request.POST['dns']

        dns_nameservers = []
        allocation_pools = []

        # 生成http提交时的body数据
        body = {
            "network":{
                "name": networkname,
                "admin_state_up": ckadmin,
                "shared":ckshare
            }
        }

        print(body)

        # 创建网络
        response = requests.post(url, data=json.dumps(body), headers=headers)
        #print("返回结果：" + str(response.status_code))
        #
        # logger.debug(response.status_code)
        # #print("返回结果：" + str(response.status_code))
        if response.status_code == 201:
            networkid  = json.loads(response.text)['network']['id']
            subNetBody = {
                "subnet":{
                    "network_id":networkid,
                    "ip_version":4,
                    "cidr":cird,
                    "name":subnetname,
                    "gateway_ip":gateway,
                    "enable_dhcp":enabledhcp,
                    "dns_nameservers":dns_nameservers,
                    "allocation_pools":allocation_pools
                }

            }
            #调用创建子网方法
            res = requests.post(OpenStackSubnet.url, data=json.dumps(subNetBody), headers=headers)
            #print(res)
            if res.status_code == 201:
                jumpurl = reverse("myadmin_network_index")
                return redirect(jumpurl + "?index=3")
            else:
                return HttpResponse("出错啦：创建子网出错！！" )
        else:
            return HttpResponse("出错啦：" + response.text)
    except Exception as err:
        return HttpResponse("出错啦："+str(err))


def delete(request,id=""):
    url_delete = url + "/" + id

    try:
        response = requests.delete(url_delete, headers=headers)
        jumpurl = reverse("myadmin_network_index")
        return redirect(jumpurl + "?index=3")
    except Exception as err:
        return HttpResponse("是出错啦：" + str(err))

def edit(request,id=0):
    try:
        # 通过render方法让html模板喧染页面
        resurl = url + "/" + str(id)
        headers = OpenStackToken.getToken()

        image = json.loads(requests.get(resurl, headers=headers).text)

        if image:
            context = {"image": image}
            print(context)
            return render(request, "myadmin/network/networkedit.html", context)
        else:
            return HttpResponse("未找到该镜像信息！！")
    except Exception as err:
        return HttpResponse("是出错啦：" + str(err))


def update(request):
     '''执行编辑信息'''
     name = request.POST['imagename']
     imageid = request.POST['imageid']
     strValue = request.POST['ragrp1']
     protected = True
     if strValue == "0":
         protected = False

     body = [
               {
                    "op": "replace",
                    "path": "/name",
                    "value": name
                },
                 {
                     "op": "replace",
                     "path": "/protected",
                     "value": protected
                 }
            ]

     #print(body)

     try:
         resurl = url + "/" + str(imageid)
         headers['Content-Type'] = "application/openstack-images-v2.1-json-patch"
         status_code = requests.patch(resurl,data=json.dumps(body), headers=headers).text
         #print(status_code)
         jumpurl = reverse("myadmin_image_index")
         return redirect(jumpurl+"?index=2")
     except Exception as err:
         return HttpResponse("是出错啦：" + str(err))


#  获取Glance ID
def get_image_id( image_name: str):
    result = json.loads(requests.get(url, headers=headers).text)
    for item in result['images']:
        if (item['name'] == image_name):
            return item['id']


# 上传glance镜像
# Image data¶ Uploads and downloads raw image data.
# These operations may be restricted to administrators. Consult your cloud operator’s documentation for details.
# /v2/images/{image_id}/file
# 镜像可以重名
def upload_image_data(image_id: str, file_path=""):
    """
    :param image_id:
    :param file_path:
    :return:
     """
    resUrl = url + "/" + image_id + "/file"
    headers['Content-Type'] = "application/octet-stream"
    response = requests.put(resUrl, data=open(file_path, 'rb').read(), headers=headers)
    #if response.status_code == 204:
    #    return {"ImageItemCreatedSuccess": response.status_code}
    return response.status_code

#  上传文件至static/uploadfile下
def saveFile(obj: object):
    BASE_DIR = Path(__file__).resolve().parent.parent
    filepath = os.path.join(BASE_DIR,'uploadfile',obj.name)
    #print("filepath="+filepath)
    f = open(filepath,'wb')
    for chunk in obj.chunks():
        f.write(chunk)
    f.close()
    return filepath

